<?php
namespace app\common\logic;

use app\common\exception\LogicException;
use app\common\model\payment\Transaction as TransactionModel;

/**
 * 支付记录逻辑
 */
class Transaction extends TransactionModel
{

    // 交易记录表
    public function addTransaction($order, $type, $time = false)
    {
        $data = $this->orderNo($order->order_no)->findOrEmpty();
        if ($data->isEmpty()) {
            $create = [
                'order_no'     => $order->order_no,
                'user_id'      => $order->user_id,
                'payment'      => $order->payment,
                'payment_type' => $type,
            ];
            $time && $create['payment_time'] = time();
            $tran = $this::create($create);
            if ( $tran->isEmpty() ) throw new LogicException('交易错误');
            
        } else if ($data->payment_type != $type) {
            $data->payment_type = $type;
            $time && $data->payment_time = time();
            if ( !$data->save() ) throw new LogicException('交易错误');
        }
    }

    public function notify($order_no, $out_trade_no = null)
    {
        $tran = $this->orderNo($order_no)->findOrEmpty();
        if (!$tran->isEmpty()) {
            $tran->payment_time = time();
            $tran->out_trade_no = $out_trade_no;
            $tran->save();
        }
    }

}
